package cn.hxzy.servlet.admin;

import cn.hxzy.entity.News;
import cn.hxzy.entity.User;
import cn.hxzy.entity.vo.PageObj;
import cn.hxzy.service.UserService;
import cn.hxzy.util.Md5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/addUser")
public class AddUserServlet extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            PageObj<User> pageObj = new PageObj<>();
            String page = req.getParameter("page");
            String size = req.getParameter("size");
            if (page != null && page != "") {
                pageObj.setPage(Integer.parseInt(page));
            }
            if (size != null && size != "") {
                pageObj.setSize(Integer.parseInt(size));
            }
            PageObj<User> all = userService.findAll(pageObj);
            req.setAttribute("addUser", all);
            req.getRequestDispatcher("/WEB-INF/jsp/admin/addUser.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String name = req.getParameter("userName");
            String password = req.getParameter("userPassword");
            String s = Md5Util.MD5(password);
            userService.add(new User(name, s));
            resp.sendRedirect("showUser");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
